<?php
/**
 * 计算指定人员的缘份
 * @author Chengxuan <chengxuan@leju.sina.com.cn>
 * @version #Id:compute.php 2010-8-7 15:56:34#
 */

require('./core/common.inc.php');
session_start();
load_weiboauth();

$context = Cls_Context::init();


if((!isset($_SESSION['last_key']) && $context->action != 'callback') || !isset($_SESSION['keys']))	//无登录(跳至登录页)
{
	$callback = pathinfo($_SERVER['SCRIPT_URI'], PATHINFO_DIRNAME).'/compute.php?action=callback';
	$class = IS_SEA ? 'SaeTOAuth' : 'WeiboOAuth';
	$cls_weibooauth = new $class( WB_AKEY , WB_SKEY  );
	$keys = $cls_weibooauth->getRequestToken();
	$aurl = $cls_weibooauth->getAuthorizeURL( $keys['oauth_token'] ,false , $callback);

	$_SESSION['keys'] = $keys;
	header("Location:{$aurl}");
	exit;
}
else								//已登录
{
	$class = IS_SEA ? 'SaeTClient' : 'WeiboClient';
	$cls_weiboclient = new $class( WB_AKEY , WB_SKEY , $_SESSION['last_key']['oauth_token'] , $_SESSION['last_key']['oauth_token_secret']  );
}


switch($context->action)
{
	case 'callback' :	//授权回调
		$class = IS_SEA ? 'SaeTOAuth' : 'WeiboOAuth';
		$o = new $class( WB_AKEY , WB_SKEY , $_SESSION['keys']['oauth_token'] , $_SESSION['keys']['oauth_token_secret']  );
		$last_key = $o->getAccessToken(  $_REQUEST['oauth_verifier'] ) ;
		$_SESSION['last_key'] = $last_key;
		
		header('Location:compute.php');
		exit;
		break;
	case 'getdata' :	//计算数据
		$me = $cls_weiboclient->verify_credentials();	//取得用户自身资料
		$user2 = $cls_weiboclient->oauth->get('http://api.t.sina.com.cn/users/show.json', array('screen_name'=>$context->nick));
		
		$response = array('success'=>false);
		
		if(!isset($user2['id']))
		{
			$response['message'] = '找不到该用户，请确认输入的微博昵称是否正确';
		}
		else
		{
			//处理结果
			$response['success'] = true;
			$response['result'] = array(
				'val'	=> cls_yuanfen::run($me['id'], $user2['id']),
				'uid'	=> $user2['id'],
				'nick'	=> $user2['screen_name']
			);
			
			//自动发表微博
			if($context->send_mblog)
			{
				$content = "我通过 @缘份计算 算出与 @{$user2['screen_name']} 之间的缘份值为 {$response['result']['val']}%。准不准呢？ by:http://yuanfen.sinaapp.com/";
				$result = $cls_weiboclient->update($content);
				if(isset($result['error']))
				{
					$response['send'] = false;
				}
				else
				{
					$response['send'] = true;
				}
			}
		}
		
		echo json_encode($response);
		
		break;
	default :	//显示页面
		$me = $cls_weiboclient->verify_credentials();	//取得用户自身资料
		include TPL_ROOT . 'compute.php';
		
}
